package com.czt.mail.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.czt.mail.config.AliOssConfig;
import com.czt.mail.entity.OssTokenVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author czt
 * @version 1.0
 * {@desc}
 * @date 2024/8/27 17:27
 */
@Service
public class OssService {

    @Autowired
    private AliOssConfig aliOssConfig;

    public OssTokenVO getToken() throws ClientException {
        //创建一个阿里云的客户端配置对象
        DefaultProfile profile = DefaultProfile.getProfile(
                aliOssConfig.getReginID(),// 地域
                aliOssConfig.getAccessKeyId(),// id
                aliOssConfig.getAccessKeySecret()//密钥
        );
        //创建客户端，用于请求和响应
        DefaultAcsClient client = new DefaultAcsClient(profile);

        //创建请求对象，用于获取临时凭证
        AssumeRoleRequest request = new AssumeRoleRequest();
        //这个名称自定义，用于区分不同的会话
        request.setRoleSessionName("app_version");
        //配置角色
        request.setRoleArn(aliOssConfig.getRoleArn());
        //临时凭证有效期 单位秒 此处配置为1小时
        request.setDurationSeconds(60*60L);
        //发送请求，获取响应数据
        AssumeRoleResponse acsResponse = client.getAcsResponse(request);

        //响应数据中包含了key、密钥、stsToken
        AssumeRoleResponse.Credentials credentials = acsResponse.getCredentials();
        String accessKeyId = credentials.getAccessKeyId();
        String accessKeySecret = credentials.getAccessKeySecret();
        String securityToken = credentials.getSecurityToken();

        //构建对象返回
        OssTokenVO ossTokenVO = OssTokenVO.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .stsToken(securityToken)
                .region("oss-" + aliOssConfig.getReginID())
                .bucket(aliOssConfig.getBucket())
                .build();

        return ossTokenVO;
    }
}
